using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RBAC.Api.Demain.ContentManagement;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.ContentManagement;

namespace RBAC.Api.Writh.CommandHandler.ContentManagement
{
    /// <summary>
    /// 删除医院处理器
    /// </summary>
    public class DeleteHospitalCommandHandler : IRequestHandler<DeleteHospitalCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<HospitalModel> baseRepositry;
        private readonly IMapper mapper;
        private readonly ILogger<DeleteHospitalCommandHandler> logger;

        public DeleteHospitalCommandHandler(
            IBaseRepositry<HospitalModel> baseRepositry,
            IMapper mapper,
            ILogger<DeleteHospitalCommandHandler> logger)
        {
            this.baseRepositry = baseRepositry;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<object>> Handle(DeleteHospitalCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = ResultCode.Success;
            result.Message = "删除医院成功";

            var strategy = baseRepositry.Context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                using (var tran = await baseRepositry.Context.Database.BeginTransactionAsync())
                {
                    try
                    {
                        // 查找要删除的医院
                        var hospital = baseRepositry.GetAll().FirstOrDefault(h => h.Id == request.Id);
                        if (hospital == null)
                        {
                            result.Code = ResultCode.Fail;
                            result.Message = $"未找到ID为{request.Id}的医院";
                            return;
                        }

                        // 执行逻辑删除
                        hospital.IsDeleted = true;
                        hospital.ModifyTime = DateTime.Now;
                        await baseRepositry.Update(hospital);

                        await tran.CommitAsync();
                        logger.LogInformation($"成功逻辑删除医院，ID: {request.Id}");
                    }
                    catch (Exception ex)
                    {
                        await tran.RollbackAsync();
                        logger.LogError(ex, $"删除医院失败，ID: {request.Id}，错误: {ex.Message}");
                        result.Code = ResultCode.Fail;
                        result.Message = $"删除医院失败: {ex.Message}";
                    }
                }
            });

            return await Task.FromResult(result);
        }
    }
}